package com.oner365.test.tree.convert;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oner365.test.tree.data.AppResourceDto;

public class TreeJsonConvertBean {

  private static final Logger LOGGER = LoggerFactory.getLogger(TreeJsonConvertBean.class);

  public static void main(String[] args) {

    JSONObject data = readJson();
    LOGGER.info("response data:{}", data);
    JSONArray treeData = data.getJSONArray("data");
    LOGGER.info("tree data:{}", treeData);
    List<AppResourceDto> list = getTreeData(treeData);
    LOGGER.info("tree data convert Bean:{}", list);
  }
  
  public static List<AppResourceDto> getTreeData(JSONArray treeData){
    List<AppResourceDto> list = new ArrayList<AppResourceDto>();
    treeData.stream().forEach(nodeData -> {
      JSONObject json = JSON.parseObject(nodeData.toString());
      AppResourceDto dto = JSON.toJavaObject(json, AppResourceDto.class);
      if (dto.getAppId() != null) {
        JSONArray resource = json.getJSONArray("resource");
        dto.setChildren(getChild(resource));
      }
      list.add(dto);
    });
    return list;
  }

  public static List<AppResourceDto> getChild(JSONArray resource) {
    List<AppResourceDto> childList = new ArrayList<AppResourceDto>();
    resource.stream().forEach(obj -> {
      LOGGER.info("tree data:{}", obj);
      JSONObject json = JSON.parseObject(obj.toString());
      AppResourceDto dto = JSON.toJavaObject(json, AppResourceDto.class);
      if (json.getJSONArray("children") != null) {
        List<AppResourceDto> childrens = getChild(json.getJSONArray("children"));
        dto.setChildren(childrens);
      }
      childList.add(dto);
    });
    return childList;
  }

  public static JSONObject readJson() {
    StringBuilder sb = new StringBuilder();
    InputStream resourceAsStream = TreeJsonConvertBean.class.getResourceAsStream("../data/firm-platform-api.json");
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream, "UTF-8"));
      for (String line = br.readLine(); line != null; line = br.readLine()) {
        if (StringUtils.isNotBlank(line)) {
          sb.append(line);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return JSON.parseObject(sb.toString());
  }

}
